/*
* @Author: gaara  
* @Date: 2020-07-10 17:04:51  
*/

const mm = require('music-metadata');
import _fs from 'fs-extra'
import { RawAsset } from "./RawAsset";

export class Audio extends RawAsset {

    downloadMode: number;

    duration: number;

    constructor(path: string) {
        super(path);

        this.downloadMode = 0;
        this.duration = 0;
    }

    static version() {
        return '2.0.1';
    }

    static defaultType(): string[] {
        return [".mp3"];
    }

    /**
     * 是否存在meta
     */
    check() {
        return new Promise((res, rej) => {

            let metaPath = this.getMetaPath();

            let json = _fs.readJSONSync(metaPath);

            mm.parseFile(this.__path__)
            .then((metadata: any) => {
                let duration: number = metadata.format.duration;
                let str = +duration.toFixed(6);
                if(str != json.duration){
                    _fs.removeSync(metaPath);
                }
            })
            .catch((err: Error) => {
                rej(err.message);
            })
            .finally(() => {
                res()
            });
        });
    }

    importPath() {
        return new Promise((res, rej) => {
            mm.parseFile(this.__path__)
                .then((metadata: any) => {
                    let duration: number = metadata.format.duration;
                    this.duration = +duration.toFixed(6);
                })
                .catch((err: Error) => {
                    rej(err.message);
                })
                .finally(() => {
                    res()
                });
        });
    }
}